package com.alibaba.citrus.cr.platform.enhance.facade.service.employee;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.util.DateUtils;
import com.alibaba.citrus.cr.platform.enhance.facade.service.role.RoleQueryServiceImpl;
import com.alibaba.citrus.cr.sales.plan.model.enums.NickTypeEnum;
import com.alibaba.cz.base.model.enterprise.constant.RoleTypeEnum;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;

import com.epoch.app.bcorder.contants.BcOrderConstants;
import com.epoch.app.bcorder.model.dto.BaselineBatchQueryRolesRequest;
import com.epoch.app.bcorder.model.dto.BaselineGetEmployeeRolesById2Request;
import com.epoch.app.bcorder.model.dto.BaselineGetRolesRequest;
import com.epoch.app.bcorder.model.dto.CreateAccountForTheFirstTimeRequest;
import com.epoch.app.bcorder.model.dto.CreateAccountForTheFirstTimeResponse;
import com.epoch.app.bcorder.model.dto.EmployeeGetCurrentLoginResponse;
import com.epoch.app.bcorder.model.dto.EmployeeResetPasswordsRequest;
import com.epoch.app.bcorder.model.dto.EmployeeSDO;
import com.epoch.app.bcorder.model.dto.RoleSDO;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.crplatformenhance.api.employeewrite.dto.CheckEmployeeRolesRequest;
import com.epoch.app.crplatformenhance.api.employeewrite.dto.CheckEmployeeSystemRequest;
import com.epoch.app.crplatformenhance.api.employeewrite.dto.CreateOrUpdateEmployeeRequest;
import com.epoch.app.crplatformenhance.api.employeewrite.dto.ImportEmployeeHandleRequest;
import com.epoch.app.crplatformenhance.api.employeewrite.dto.UpdateEmployeeRequest;
import com.epoch.app.crplatformenhance.api.employeewrite.service.EmployeeWriteService;
import com.epoch.app.crplatformenhance.api.organizationquery.service.OrganizationQueryService;
import com.epoch.app.crplatformenhance.contants.CrPlatformEnhanceConstants;
import com.epoch.app.crplatformenhance.domain.customeraddress.dto.BatchQueryAddressByConditionRequest;
import com.epoch.app.crplatformenhance.domain.customeraddress.model.CustomerAddress;
import com.epoch.app.crplatformenhance.domain.customeraddress.service.CustomerAddressService;
import com.epoch.app.crplatformenhance.dto.request.EmployeeImportRequest;
import com.epoch.app.crplatformenhance.dto.request.IdQueryRequest;
import com.epoch.app.crplatformenhance.dto.request.ImportRequest;
import com.epoch.app.crplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.crplatformenhance.enums.RoleQueryTypeEnum;
import com.epoch.app.crplatformenhance.model.dto.*;
import com.epoch.app.crplatformenhance.rolequery.dto.GetRoleListToPageRequest;
import com.epoch.app.crplatformenhance.rolequery.service.RoleQueryService;
import com.epoch.app.crplatformenhance.sdo.OrganizationSDO;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StopWatch;

/**
 * @author:suqing.tjf
 * @date:2021/11/12
 */
@Component
@Primary
public class EmployeeWriteServiceImpl implements EmployeeWriteService {

    private static final Log log = Log.getLogger(EmployeeWriteServiceImpl.class);

    @Resource
    private CrPlatformEnhanceService crPlatformEnhanceService;

    @Resource
    private BcOrderService bcOrderService;

    @Resource
    private OrganizationQueryService organizationQueryService;

    @Resource
    private CustomerAddressService customerAddressService;

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private RoleQueryService roleQueryService;

    private static final String MN_GROUP_ORG_ID = "1";
    private static final String ADMIN_ROLE_CODE = "administrator";

    //校验大小写英文字母和汉字
    private static final String regex1 = "^[a-zA-Z\\u4e00-\\u9fa5]+$";
    //校验大小写英文字母、汉字和下划线
    private static final String regex2 = "^[a-zA-Z0-9\\u4E00-\\u9FA5_]+$";
    //员工扩展字段中的标
    private final static String CUSTOMER_CODE = "customerCode";
    private final static String CUSTOMER_ADDRESS_CODE = "customerAddressCode";
    private final static String NICK_TYPE = "nickType";
    private final static String SUPERVISOR_NAME = "supervisorName";
    private final static String SUPERVISOR_WORK_ID = "supervisorWorkId";
    private final static String FROM_SYS = "APP_OTS";
    private final static String BUSINESS_TYPE = "1";
    /**
     * importEmployeeHandle
     *
     * @param importEmployeeHandleRequest
     */
    @Override
    @FacadeInvoker
    public Result<List<EmployeeImportRequest>> importEmployeeHandle(ImportEmployeeHandleRequest importEmployeeHandleRequest) {
        List<EmployeeImportRequest> request = importEmployeeHandleRequest.getImportEmployeeHandleRequest();
        if (CollectionUtils.isEmpty(request)) {
            return Result.success(Lists.newArrayList());
        }
        EmployeeGetCurrentLoginResponse loginUser = bcOrderService.employeeGetCurrentLogin();
        log.info("EmployeeWriteServiceImpl_importEmployeeHandle_loginUser={}", JSONObject.toJSONString(loginUser));
        if (loginUser == null) {
            setRequestErrorMessage(request, ErrorMessage.code("OTS-01-001-01-16-025", null).getDisplayErrorMessage());
            return Result.success(request);
        }
        //校验当前登陆员工权限
        String userOrganizationId = loginUser.getRelatedOrganizationId();
        if (Strings.isBlank(userOrganizationId) || Strings.isBlank(loginUser.getRelatedOrganizationType())) {
            setRequestErrorMessage(request, ErrorMessage.code("OTS-01-001-01-16-026", null).getDisplayErrorMessage());
            return Result.success(request);
        }

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        //当登录用户是蒙牛集团的，只能新增6000下组织员工
        Map<String,OrganizationSDO> mnOrgMap = null;
        if (MN_GROUP_ORG_ID.equals(userOrganizationId)) {
            //获取常温事业部6000下组织
            Result<List<OrganizationSDO>> mnOrgResult = organizationQueryService.getMnOrderOrganizations();
            if (mnOrgResult!=null && CollectionUtils.isNotEmpty(mnOrgResult.getResult())) {
                mnOrgMap = mnOrgResult.getResult().stream().collect(Collectors.toMap(OrganizationSDO::getId, Function.identity(),(v1, v2)->v1));
            }
        }

        //查询当前登陆员工所在组织及下属组织
        List<OrganizationSDO> userDownOrgList = getLoginUserAllDownOrgs(loginUser);
        Map<Optional<String>, OrganizationSDO> userAllDownOrgMap = userDownOrgList.stream().collect(Collectors.toMap(organizationSDO -> Optional.ofNullable(organizationSDO.getCode()), o -> o));

        //查询所有角色
        Result<List<RoleSDO>> roleResult = crPlatformEnhanceService.getRoles(GetRolesRequest.builder().type(1).belongOrganizationId("1").build());
        Map<String, String> allRoleMap = Nullable.stream(roleResult.getResult()).collect(Collectors.toMap(RoleSDO::getName, RoleSDO::getId));
        //查询超级管理员角色
        Result<RoleSDO> administratorRoleSDOResult = crPlatformEnhanceService.getRole(GetRoleRequest.builder()
                .code(ADMIN_ROLE_CODE)
                .build());
        String personInChargeRoleId = Optional.ofNullable(administratorRoleSDOResult)
                .filter(Result::isSuccess)
                .map(Result::getResult)
                .map(RoleSDO::getId)
                .orElse(null);

        stopWatch.stop();
        log.info("EmployeeWriteServiceImpl_stopWatch_pre_data={}",stopWatch.getTotalTimeMillis());

        log.info("EmployeeWriteServiceImpl_importEmployeeHandle_initPassword={}",CrPlatformEnhanceConstants.EMPLOYEE_PASSWORD());
        //入参必填校验：姓名、账号、手机号、所属组织编码、工号
        for (EmployeeImportRequest importRequest : request) {
            log.info("EmployeeWriteServiceImpl_importEmployeeHandle_importEmployeeRequest={}", JSONObject.toJSONString(importRequest));
            try {
                //去除空格
                if (!trimBean(importRequest)) {
                    importRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-024", "导入员工数据去除空格异常").getDisplayErrorMessage());
                    continue;
                }
                if (Strings.isBlank(importRequest.getWorkId())) {
                    importRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-030", null).getDisplayErrorMessage());
                    continue;
                }
                if (Strings.isBlank(importRequest.getName())) {
                    importRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-001", null).getDisplayErrorMessage());
                    continue;
                }
                if (!importRequest.getName().matches(regex1)) {
                    importRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-022", null).getDisplayErrorMessage());
                    continue;
                }
                if (Strings.isBlank(importRequest.getNick())) {
                    importRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-002", null).getDisplayErrorMessage());
                    continue;
                }
                if (!importRequest.getNick().matches(regex2)) {
                    importRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-023", null).getDisplayErrorMessage());
                    continue;
                }
                if (Strings.isBlank(importRequest.getPhone())) {
                    importRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-003", null).getDisplayErrorMessage());
                    continue;
                }
                if (Strings.isBlank(importRequest.getOrganizationCode())) {
                    importRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-004", null).getDisplayErrorMessage());
                    continue;
                }
                if (Strings.isBlank(importRequest.getIdentityCardNumber())) {
                    importRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-031", null).getDisplayErrorMessage());
                    continue;
                }

                StopWatch sw = new StopWatch();
                sw.start("ctsCreateAccount");
                //校验导入组织是否属于当前用户组织下
                OrganizationSDO importEmployeeOrg = userAllDownOrgMap.get(Optional.ofNullable(importRequest.getOrganizationCode()));
                if (ObjectUtils.isEmpty(importEmployeeOrg)) {
                    importRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-027", null).getDisplayErrorMessage());
                    continue;
                }
                //需要新增的组织id(一个员工只能关联一个组织)
                importRequest.setRelationOrganizationId(importEmployeeOrg.getId());

                if(MN_GROUP_ORG_ID.equals(userOrganizationId) && mnOrgMap.get(importRequest.getRelationOrganizationId()) == null){
                    importRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-038", null).getDisplayErrorMessage());
                    continue;
                }

                CtsCreateAccountRequest createAccountRequest = new CtsCreateAccountRequest();
                createAccountRequest.setWorkId(importRequest.getWorkId());
                createAccountRequest.setName(importRequest.getName());
                createAccountRequest.setAccount(importRequest.getNick());
                createAccountRequest.setPassword(CrPlatformEnhanceConstants.EMPLOYEE_PASSWORD());
                createAccountRequest.setIdentityCard(importRequest.getIdentityCardNumber());
                createAccountRequest.setPhone(importRequest.getPhone());
                createAccountRequest.setEmail(importRequest.getEmail());
                createAccountRequest.setSupervisorWorkId(importRequest.getSupervisorWorkId());
                createAccountRequest.setSupervisorName(importRequest.getSupervisorName());
                createAccountRequest.setValidStartDate(DateUtils.toDateStr(importRequest.getValidStartDate(),DateUtils.DATETIME_FORMAT));
                createAccountRequest.setValidEndDate(DateUtils.toDateStr(importRequest.getValidEndDate(),DateUtils.DATETIME_FORMAT));
                createAccountRequest.setOrganizationId(importRequest.getRelationOrganizationId());
                createAccountRequest.setFromSys(FROM_SYS);
                createAccountRequest.setBusinessType(BUSINESS_TYPE);
                createAccountRequest.setCreatorId(loginUser.getEmployeeId());
                //features里打标：customerCode、nickType、supervisorName、supervisorWorkId
                createAccountRequest.setFeatures(convertFeaturesMap(importRequest));
                Result<String> createResult = crPlatformEnhanceService.ctsCreateAccount(createAccountRequest);
                if(createResult==null || StringUtils.isBlank(createResult.getResult())){
                    importRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-006", createResult.getMessage()).getDisplayErrorMessage());
                    continue;
                }
                importRequest.setId(createResult.getResult());

//                EmployeeResetPasswordsRequest resetPasswordsRequest = new EmployeeResetPasswordsRequest();
//                resetPasswordsRequest.setEmployeeId(createResult.getResult());
//                resetPasswordsRequest.setPassword(CrPlatformEnhanceConstants.EMPLOYEE_PASSWORD());
//                EmployeeSDO apiContext = new EmployeeSDO();
//                apiContext.setId(loginUser.getEmployeeId());
//                apiContext.setBelongOrganizationId(loginUser.getBelongOrganizationId());
//                resetPasswordsRequest.setApiContext(apiContext);
//                Result<Boolean> updateResult = bcOrderService.employeeResetPasswords(resetPasswordsRequest);
//                if(updateResult==null || !updateResult.isSuccess()){
//                    log.info("EmployeeWriteServiceImpl_importEmployeeHandle_employeeResetPasswords_error,id={},message={}", importRequest.getId(), updateResult.getMessage());
//                }

                sw.stop();

                sw.start("createAccountSendEmail");
                //员工创建成功后发送邮件，没有填写邮箱就跳过
                if (importRequest.getEmail() != null && Strings.isNotBlank(importRequest.getEmail())) {
                    createAccountSendEmail(importRequest);
                }
                sw.stop();
                log.info("EmployeeWriteServiceImpl_importEmployeeHandle_foreach_sw_print1,id_{},print={}",importRequest.getId(), sw.prettyPrint());
                if (Strings.isBlank(importRequest.getRoleName())) {
                    continue;
                }
                sw.start("existRole");
                //根据逗号切割
                List<String> importEmployeeRoles = Lists.newArrayList(Arrays.asList(importRequest.getRoleName().split("[,，]")));
                List<String> importEmployeeRoleIdList = importEmployeeRoles.stream().map(allRoleMap::get).filter(Strings::isNotBlank).collect(Collectors.toList());
                log.info("EmployeeWriteServiceImpl_importEmployeeHandle_importEmployeeRoles,id_{}_split_result={},filter_result={}",
                        importRequest.getId(), JSONObject.toJSONString(importEmployeeRoles), JSONObject.toJSONString(importEmployeeRoleIdList));

                //需要判断传入的角色名称是否存在，不存在的角色更新以后员工数据会有问题
                if (CollectionUtils.isEmpty(importEmployeeRoleIdList)) {
                    importRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-012", null).getDisplayErrorMessage());
                    continue;
                }
                sw.stop();
                sw.start("createRole");
                //========更新角色参照oms的接口
                //如果操作的是自己，并且删除了自己的负责人角色，则报错
                if (personInChargeRoleId != null) {
                    // 被编辑员工的角色列表
                    Result<List<RoleSDO>> employeeRolesResult = crPlatformEnhanceService.getEmployeeRoles(GetEmployeeRolesRequest.builder()
                            .id(Optional.ofNullable(importRequest.getId()).orElse(null))
                            .build());//获取一个员工的所有角色
                    log.info("EmployeeWriteServiceImpl_importEmployeeHandle_getEmployeeRoles,id_{}_getEmployeeRoles={}", importRequest.getId(), JSONObject.toJSONString(employeeRolesResult));
                    List<RoleSDO> employeeRoles = Optional.ofNullable(employeeRolesResult)
                            .filter(Result::isSuccess)
                            .map(Result::getResult)
                            .orElse(Collections.emptyList());
                    // 被编辑员工的角色ID列表
                    List<String> existRoleIds = employeeRoles.stream()
                            .filter(roleSDO -> Objects.equals(roleSDO.getType(), 1))
                            .filter(Objects::nonNull)
                            .map(RoleSDO::getId)
                            .filter(Objects::nonNull)
                            .collect(Collectors.toList());

                    //更新时要把已关联的角色也放进去
                    //                employeeRoles.addAll(existRoleIds);
                    //                employeeRoles = employeeRoles.stream().distinct().collect(Collectors.toList());
                    // 如果操作的是自己，并且删除了自己的负责人角色，则报错
                    if (Objects.equals(importRequest.getId(), loginUser.getEmployeeId())
                            && existRoleIds.contains(personInChargeRoleId)
                            && employeeRoles.stream().noneMatch(
                            roleId -> Objects.equals(roleId, personInChargeRoleId))) {
                        importRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-007", null).getDisplayErrorMessage());
                        continue;
                    }
                }

                //全量更新一个员工的所有角色
                Result<Boolean> editResult = crPlatformEnhanceService.editEmployeeRoles(EditEmployeeRolesRequest.builder()
                        .employeeId(Optional.ofNullable(importRequest.getId()).orElse(null))
                        .belongOrganizationId(Optional.ofNullable(importRequest.getBelongOrganizationId()).orElse(null))
                        .roleIds(importEmployeeRoleIdList)
                        .operatorId(Optional.ofNullable(loginUser.getEmployeeId()).orElse(null))
                        .build());//更新功能角色
                log.info("EmployeeWriteServiceImpl_importEmployeeHandle_editEmployeeRoles,id_{}_response={}", importRequest.getId(), JSONObject.toJSONString(editResult));
                if (!editResult.isSuccess() || !editResult.getResult()) {
                    importRequest.setErrorMessage(editResult.getMessage());
                }
                sw.stop();

                log.info("EmployeeWriteServiceImpl_importEmployeeHandle_foreach_sw_print2,id_{},print={}",importRequest.getId(), sw.prettyPrint());

            } catch (Exception e) {
                log.error("EmployeeWriteServiceImpl_importEmployeeHandle_occer_error", e);
                importRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-024", e.getMessage()).getDisplayErrorMessage());
                continue;
            }
        }
        return Result.success(request);
    }

    private Map<String, String> convertFeaturesMap(EmployeeImportRequest employeeRequest) {
        Map<String, String> featuresMap = new HashMap<>();
        if (Strings.isNotBlank(employeeRequest.getCustomerCode())) {
            BatchQueryCustomers2Response result = crPlatformEnhanceService.batchQueryCustomers2(BatchQueryCustomers2Request.builder()
                    .codes(Lists.newArrayList(employeeRequest.getCustomerCode())).build());
            if (CollectionUtils.isNotEmpty(result.getResult())) {
                featuresMap.put(CUSTOMER_CODE, employeeRequest.getCustomerCode());
                featuresMap.put(NICK_TYPE, NickTypeEnum.CUSTOMER.getType().toString());
            } else {
                employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-032", null).getDisplayErrorMessage());
            }
        }
        if (Strings.isNotBlank(employeeRequest.getCustomerAddressCode())) {
            Result<List<CustomerAddress>> result = customerAddressService.batchQueryAddressByCondition(BatchQueryAddressByConditionRequest.builder()
                    .addressCodes(Lists.newArrayList(employeeRequest.getCustomerAddressCode())).build());
            if (CollectionUtils.isNotEmpty(result.getResult())) {
                featuresMap.put(CUSTOMER_ADDRESS_CODE, employeeRequest.getCustomerAddressCode());
            } else {
                employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-013", null).getDisplayErrorMessage());
            }
        }
        if (StringUtils.isNotEmpty(employeeRequest.getSupervisorName())) {
            featuresMap.put(SUPERVISOR_NAME, employeeRequest.getSupervisorName());
        }
        if (StringUtils.isNotEmpty(employeeRequest.getSupervisorWorkId())) {
            featuresMap.put(SUPERVISOR_WORK_ID, employeeRequest.getSupervisorWorkId());
        }
        log.info("EmployeeWriteServiceImpl_importEmployeeHandle_featuresMap={}", JSONObject.toJSONString(featuresMap));
        return featuresMap;
    }

    private void createAccountSendEmail(EmployeeImportRequest employeeRequest){
        CreateAccountForTheFirstTimeResponse response = bcOrderService.createAccountForTheFirstTime(CreateAccountForTheFirstTimeRequest.builder()
                .title("2")
                .employeeId(employeeRequest.getId())
                .nick(employeeRequest.getNick())
                .email(employeeRequest.getEmail())
                .password(CrPlatformEnhanceConstants.EMPLOYEE_PASSWORD()).build());
        log.info("EmployeeWriteServiceImpl_importEmployeeHandle_createAccount_sendEmail_result={},employee_id={}", JSONObject.toJSONString(response), employeeRequest.getId());
        //邮件发送失败
        if (response==null || !response.getSuccess()) {
            employeeRequest.setErrorMessage(ErrorMessage.code("OTS-01-001-01-16-014", null).getDisplayErrorMessage());
        }
    }

    private static <T extends ImportRequest> List<T> setRequestErrorMessage(List<T> requestList, String errorMessage){
        requestList.forEach(importRequest -> importRequest.setErrorMessage(errorMessage));
        return requestList;
    }

    private static boolean trimBean(Object object) {
        if (null == object) {
            return true;
        }
        try {
            for (Field f : object.getClass().getDeclaredFields()) {
                if (f.getGenericType().toString().equals("class java.lang.String")) {
                    f.setAccessible(true);
                    String value = (String) f.get(object);
                    if (null == value) {
                        continue;
                    }
                    value = value.trim();
                    f.set(object, value);
                }
            }
        } catch (Exception e) {
            log.error(JSONObject.toJSONString(object) + "导入员工时去除空格报错" + e);
            return false;
        }
        return true;
    }

    /**
     * 创建员工
     * 1.判断创建员工的关联组织是否在登录人组织以下，不在抛错
     * 2.判断创建员工的关联组织是否在6000组织以下，不在抛错
     * 3.根据工号+状态（1,2）查询员工，如果存在员工
     * 把该员工的基础信息档案更新，关联组织更新，return
     * 4. 工号不存在员工 ，还需校验字段唯一性
     * 根据账号查询员工，存在员工抛错
     * 根据邮箱查询员工，存在员工抛错
     * 根据手机号查询员工，存在员工抛错
     * 5.调用中台创建员工接口，调用中台关联员工组织接口
     * @param createOrUpdateEmployeeRequest
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<String> createOrUpdateEmployee(CreateOrUpdateEmployeeRequest createOrUpdateEmployeeRequest) {
        EmployeeGetCurrentLoginResponse loginUser = bcOrderService.employeeGetCurrentLogin();
        if (loginUser == null || Strings.isBlank(loginUser.getRelatedOrganizationId())) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-021"));
        }

        //校验员工创建参数
        checkEmployeeCreateParams(createOrUpdateEmployeeRequest);

        //新增修改员工的组织，只能是登录用户组织下
        if(!checkEmployeeOrg((String) createOrUpdateEmployeeRequest.getRelationOrganizationIdList().get(0), loginUser)){
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-037"));
        }

        //当登录用户是蒙牛集团的，只能新增6000下组织员工
        if(!checkEmployee6000Org((String) createOrUpdateEmployeeRequest.getRelationOrganizationIdList().get(0), loginUser)){
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-038"));
        }

        CtsCreateAccountRequest createAccountRequest = new CtsCreateAccountRequest();
        createAccountRequest.setWorkId(createOrUpdateEmployeeRequest.getWorkId());
        createAccountRequest.setName(createOrUpdateEmployeeRequest.getName());
        createAccountRequest.setAccount(createOrUpdateEmployeeRequest.getNick());
        createAccountRequest.setPassword(createOrUpdateEmployeeRequest.getPassword());
        createAccountRequest.setIdentityCard(createOrUpdateEmployeeRequest.getIdentityCardNumber());
        createAccountRequest.setPhone(createOrUpdateEmployeeRequest.getPhone());
        createAccountRequest.setEmail(createOrUpdateEmployeeRequest.getEmail());
        createAccountRequest.setSupervisorWorkId(createOrUpdateEmployeeRequest.getSupervisorWorkId());
        createAccountRequest.setSupervisorName(createOrUpdateEmployeeRequest.getSupervisorName());
        createAccountRequest.setValidStartDate(DateUtils.toDateStr(createOrUpdateEmployeeRequest.getValidStartDate(),DateUtils.DATETIME_FORMAT));
        createAccountRequest.setValidEndDate(DateUtils.toDateStr(createOrUpdateEmployeeRequest.getValidEndDate(),DateUtils.DATETIME_FORMAT));
        createAccountRequest.setOrganizationId((String) createOrUpdateEmployeeRequest.getRelationOrganizationIdList().get(0));
        createAccountRequest.setFromSys(FROM_SYS);
        createAccountRequest.setBusinessType(BUSINESS_TYPE);
        createAccountRequest.setCreatorId(loginUser.getEmployeeId());
        Result<String> createResult = crPlatformEnhanceService.ctsCreateAccount(createAccountRequest);

//        if (createResult!=null && createResult.isSuccess()) {
//            EmployeeResetPasswordsRequest resetPasswordsRequest = new EmployeeResetPasswordsRequest();
//            resetPasswordsRequest.setEmployeeId(createResult.getResult());
//            resetPasswordsRequest.setPassword(createOrUpdateEmployeeRequest.getPassword());
//            EmployeeSDO apiContext = new EmployeeSDO();
//            apiContext.setId(loginUser.getEmployeeId());
//            apiContext.setBelongOrganizationId(loginUser.getBelongOrganizationId());
//            resetPasswordsRequest.setApiContext(apiContext);
//            Result<Boolean> updateResult = bcOrderService.employeeResetPasswords(resetPasswordsRequest);
//            if(updateResult==null || !updateResult.isSuccess()){
//                log.info("EmployeeWriteServiceImpl_createOrUpdateEmployee_employeeResetPasswords_error,id={},message={}", createResult.getResult(), updateResult.getMessage());
//            }
//        }

        return createResult;
    }

    private void checkEmployeeCreateParams(CreateOrUpdateEmployeeRequest createOrUpdateEmployeeRequest){
        if (Strings.isBlank(createOrUpdateEmployeeRequest.getWorkId())) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-030"));
        }
        if (Strings.isBlank(createOrUpdateEmployeeRequest.getName())) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-001"));
        }
        if (Strings.isBlank(createOrUpdateEmployeeRequest.getNick())) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-002"));
        }
        if (Strings.isBlank(createOrUpdateEmployeeRequest.getPhone())) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-003"));
        }
        if (Strings.isBlank(createOrUpdateEmployeeRequest.getIdentityCardNumber())) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-031"));
        }
        if (Strings.isBlank(createOrUpdateEmployeeRequest.getPassword())) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-020"));
        }
        if (CollectionUtils.isEmpty(createOrUpdateEmployeeRequest.getRelationOrganizationIdList())) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-005"));
        }
    }

    /**
     * updateEmployee
     *
     * @param updateEmployeeRequest
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<Boolean> updateEmployee(UpdateEmployeeRequest updateEmployeeRequest) {
        EmployeeGetCurrentLoginResponse loginUser = bcOrderService.employeeGetCurrentLogin();
        if (loginUser == null || Strings.isBlank(loginUser.getRelatedOrganizationId())) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-021"));
        }

        //校验员工更新参数
        checkEmployeeUpdateParams(updateEmployeeRequest);

        //校验员工所属系统
        CheckEmployeeSystemRequest checkEmployeeSystemRequest = new CheckEmployeeSystemRequest();
        checkEmployeeSystemRequest.setLoginUserId(loginUser.getEmployeeId());
        checkEmployeeSystemRequest.setUpdateUserId(updateEmployeeRequest.getId());
        Result<Boolean> checkResult = checkEmployeeSystem(checkEmployeeSystemRequest);
        if (!checkResult.isSuccess()){
            return Result.fail(checkResult.getErrorCode(),checkResult.getMessage());
        }

        //校验员工组织权限
        if(!checkEmployeeOrg((String) updateEmployeeRequest.getRelationOrganizationIdList().get(0), loginUser)){
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-028"));
        }

        //当登录用户是蒙牛集团的，只能变更到常温事业部6000下组织
        if(!checkEmployee6000Org((String) updateEmployeeRequest.getRelationOrganizationIdList().get(0), loginUser)){
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-029"));
        }

        //校验员工是否是销售负责人
        checkEmployeePrincipal(updateEmployeeRequest.getId(), (String) updateEmployeeRequest.getRelationOrganizationIdList().get(0), loginUser);

        CtsModifyAccountRequest modifyAccountRequest = new CtsModifyAccountRequest();
        modifyAccountRequest.setEmployeeId(updateEmployeeRequest.getId());
        modifyAccountRequest.setName(updateEmployeeRequest.getName());
        modifyAccountRequest.setAccount(updateEmployeeRequest.getNick());
        modifyAccountRequest.setPhone(updateEmployeeRequest.getPhone());
        modifyAccountRequest.setEmail(updateEmployeeRequest.getEmail());
        modifyAccountRequest.setSupervisorWorkId(updateEmployeeRequest.getSupervisorWorkId());
        modifyAccountRequest.setSupervisorName(updateEmployeeRequest.getSupervisorName());
        modifyAccountRequest.setValidStartDate(DateUtils.toDateStr(updateEmployeeRequest.getValidStartDate(),DateUtils.DATE_FORMAT));
        modifyAccountRequest.setValidEndDate(DateUtils.toDateStr(updateEmployeeRequest.getValidEndDate(),DateUtils.DATE_FORMAT));
        modifyAccountRequest.setOrganizationId((String) updateEmployeeRequest.getRelationOrganizationIdList().get(0));
        modifyAccountRequest.setSender(FROM_SYS);
        modifyAccountRequest.setFromSys(FROM_SYS);
        modifyAccountRequest.setBusinessType(BUSINESS_TYPE);
        modifyAccountRequest.setModifierId(loginUser.getEmployeeId());
        return crPlatformEnhanceService.ctsModifyAccount(modifyAccountRequest);
    }

    private void checkEmployeeUpdateParams(UpdateEmployeeRequest updateEmployeeRequest){
        if (Strings.isBlank(updateEmployeeRequest.getId())) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-015"));
        }
        if (Strings.isBlank(updateEmployeeRequest.getWorkId())) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-030"));
        }
        if (Strings.isBlank(updateEmployeeRequest.getName())) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-001"));
        }
        if (Strings.isBlank(updateEmployeeRequest.getNick())) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-002"));
        }
        if (Strings.isBlank(updateEmployeeRequest.getPhone())) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-003"));
        }
        if (CollectionUtils.isEmpty(updateEmployeeRequest.getRelationOrganizationIdList())) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-005"));
        }
    }

    /**
     * 校验员工是否是销售负责人
     *
     * @param employeeId
     * @param updateOrganizationId
     * @return
     */
    private void checkEmployeePrincipal(String employeeId, String updateOrganizationId, EmployeeGetCurrentLoginResponse loginUser) {
        //判断有没有分配为销售负责人
        PageQueryAddressListResponse addressListResponse = crPlatformEnhanceService.pageQueryAddressList(PageQueryAddressListRequest.builder().principal(employeeId).build());
        if (!addressListResponse.getSuccess()) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-018"));
        }
        PageQueryCustomerScopeResponse customerScopeResponse = crPlatformEnhanceService.pageQueryCustomerScope(PageQueryCustomerScopeRequest.builder().principal(employeeId).build());
        if (!customerScopeResponse.getSuccess()) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-019"));
        }
        if (addressListResponse.getSuccess() && addressListResponse.getTotal() == 0 && customerScopeResponse.getSuccess() && customerScopeResponse.getTotal() == 0) {
            return;
        }
        //查询员工所在的组织
        Result<List<OrganizationSDO>> employeeOrgResult = crPlatformEnhanceService.getEmployeeOrganizations(GetEmployeeOrganizationsRequest.builder()
                .employeeId(employeeId)
                .belongOrganizationId("1")
                .build());
        if (!employeeOrgResult.isSuccess()) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-016"));
        }
        String oldEmployeeOrgId = null;
        if (CollectionUtils.isNotEmpty(employeeOrgResult.getResult()) && employeeOrgResult.getResult().get(0).getId() != null) {
            oldEmployeeOrgId = employeeOrgResult.getResult().get(0).getId();
        }
        //如果是销售负责人，判断组织id是否有变更，无变更就允许修改
        if (updateOrganizationId == null) {
            if (oldEmployeeOrgId == null) {
                return;
            }
        } else {
            if (updateOrganizationId.equals(oldEmployeeOrgId)) {
                return;
            }
        }
        throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-017"));
    }

    /**
     * 新增修改员工的组织，只能是当前用户组织下
     * @param updateOrganizationId
     * @param loginUser
     * @return
     */
    private Boolean checkEmployeeOrg(String updateOrganizationId, EmployeeGetCurrentLoginResponse loginUser){
        List<OrganizationSDO> userDownOrgList = getLoginUserAllDownOrgs(loginUser);
        Map<String, OrganizationSDO> userAllDownOrgMap = userDownOrgList.stream().collect(Collectors.toMap(organizationSDO -> organizationSDO.getId(), o -> o));
        boolean b = userAllDownOrgMap.get(updateOrganizationId) != null ? true:false;
        return b;
    }

    /**
     * 新增修改员工的组织，只能是6000下组织
     * @param updateOrganizationId
     * @return
     */
    private Boolean checkEmployee6000Org(String updateOrganizationId, EmployeeGetCurrentLoginResponse loginUser){
        if (!MN_GROUP_ORG_ID.equals(loginUser.getRelatedOrganizationId())) {
            return true;
        }
        Result<List<OrganizationSDO>> mnOrgResult = organizationQueryService.getMnOrderOrganizations();//返回的组织包含蒙牛集团1
        if (mnOrgResult!=null && CollectionUtils.isNotEmpty(mnOrgResult.getResult())) {
            Map<String,OrganizationSDO> mnOrgMap = mnOrgResult.getResult().stream().collect(Collectors.toMap(OrganizationSDO::getId, Function.identity(),(v1, v2)->v1));
            if(mnOrgMap.get(updateOrganizationId) == null){
                return false;
            }
        }
        return true;
    }

    /**
     * 查询当前登陆员工所在组织及下属所有组织
     * @param loginUser
     * @return
     */
    private List<OrganizationSDO> getLoginUserAllDownOrgs(EmployeeGetCurrentLoginResponse loginUser){
        IdQueryRequest getUserDownOrgReq = new IdQueryRequest();
        getUserDownOrgReq.setId(loginUser.getRelatedOrganizationId());
        getUserDownOrgReq.setType(OrganizationTypeEnum.SALES_DEPARTMENT.getCode());
        Result<List<OrganizationSDO>> userDownOrgResult = organizationQueryService.getAllChildOrganizationList(getUserDownOrgReq);
        log.info("EmployeeWriteServiceImpl_getLoginUserAllDownOrgs_result={}", JSONObject.toJSONString(userDownOrgResult));
        List<OrganizationSDO> userDownOrgList = new ArrayList<>();
        if (userDownOrgResult!=null && CollectionUtils.isNotEmpty(userDownOrgResult.getResult())) {
            userDownOrgList = userDownOrgResult.getResult();
        }
        return userDownOrgList;
    }

    /**
     * 编辑员工角色时，根据登录用户展示的角色列表，校验新加的角色是否在其中
     * @param checkEmployeeRolesRequest
     */
    @Override
    @FacadeInvoker
    public Result<Boolean> checkEmployeeRoles(CheckEmployeeRolesRequest checkEmployeeRolesRequest) {
        if(CollectionUtils.isEmpty(checkEmployeeRolesRequest.getRoleIdList())){
            checkEmployeeRolesRequest.setRoleIdList(new ArrayList());
        }

        //获取当前用户的展示角色列表
        GetRoleListToPageRequest getRoleListToPageRequest = new GetRoleListToPageRequest();
        getRoleListToPageRequest.setPermissionType(RoleTypeEnum.FUNCTION.getNo());
        Result<List<RoleSDO>> roleListResult = roleQueryService.getRoleListToPage(getRoleListToPageRequest);
        if(Objects.isNull(roleListResult) || CollectionUtils.isEmpty(roleListResult.getResult())){
            throw new FacadeException(ErrorMessage.code("OTS-01-003-01-15-029"));
        }
        List<String> allowEditRoleIds = roleListResult.getResult().stream().map(x->x.getId()).collect(Collectors.toList());
        allowEditRoleIds.add(RoleQueryServiceImpl.ADMIN_ROLE_ID);
        Set<String> checkBelongOrganizationIds = roleListResult.getResult().stream().map(x->x.getBelongOrganizationId()).collect(Collectors.toSet());

        //获取员工当前拥有的角色
        List<String> employeeRoleIds = new ArrayList<>();
        BaselineGetEmployeeRolesById2Request getEmployeeRolesByIdRequest = new BaselineGetEmployeeRolesById2Request();
        getEmployeeRolesByIdRequest.setBelongOrganizationId(RoleQueryTypeEnum.OTS.getBelongOrganizationId());
        getEmployeeRolesByIdRequest.setEmployeeId(checkEmployeeRolesRequest.getEmployeeId());
        Result<List<RoleSDO>> employeeRolesResult = baseDataService.baselineGetEmployeeRolesById2(getEmployeeRolesByIdRequest);
        if(employeeRolesResult!=null && CollectionUtils.isNotEmpty(employeeRolesResult.getResult())){
            List<RoleSDO> employeeRoles = employeeRolesResult.getResult().stream().filter(x->RoleTypeEnum.FUNCTION.getNo().equals(x.getType())).collect(Collectors.toList());
            employeeRoleIds = employeeRoles.stream().map(x->x.getId()).collect(Collectors.toList());
        }
        //增加删除的角色不为空，校验角色的belongOrganizationId
        List<String> addEmployeeRoleIds = (List<String>) CollectionUtils.subtract(checkEmployeeRolesRequest.getRoleIdList(), employeeRoleIds);
        List<String> delEmployeeRoleIds = (List<String>) CollectionUtils.subtract(employeeRoleIds, checkEmployeeRolesRequest.getRoleIdList());
        addEmployeeRoleIds.addAll(delEmployeeRoleIds);
        if(CollectionUtils.isNotEmpty(addEmployeeRoleIds)){
            BaselineBatchQueryRolesRequest batchQueryRolesRequest = new BaselineBatchQueryRolesRequest();
            batchQueryRolesRequest.setIdList(addEmployeeRoleIds);
            Result<List<RoleSDO>> rolesResult = baseDataService.baselineBatchQueryRoles(batchQueryRolesRequest);
            if(rolesResult!=null && CollectionUtils.isNotEmpty(rolesResult.getResult())){
                Set<String> rolesBelongOrganizationIds = rolesResult.getResult().stream().map(x->x.getBelongOrganizationId()).collect(Collectors.toSet());
                if(!CollectionUtils.containsAll(checkBelongOrganizationIds,rolesBelongOrganizationIds)){
                    throw new FacadeException(ErrorMessage.code("OTS-01-003-01-15-029"));
                }
            }
        }

        return Result.success(true);
    }

    /**
     * 编辑员工时，根据登录用户的所属系统，只能修改同一系统的员工
     * @param checkEmployeeSystemRequest
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<Boolean> checkEmployeeSystem(CheckEmployeeSystemRequest checkEmployeeSystemRequest) {
        //校验员工的所属系统
        BaselineGetEmployeeRolesById2Request queryLoginUserRoleReq = new BaselineGetEmployeeRolesById2Request();
        //queryLoginUserRoleReq.setBelongOrganizationId(RoleQueryTypeEnum.OTS.getBelongOrganizationId());
        queryLoginUserRoleReq.setEmployeeId(checkEmployeeSystemRequest.getLoginUserId());
        Result<List<RoleSDO>> loginUserRolesResult = baseDataService.baselineGetEmployeeRolesById2(queryLoginUserRoleReq);
        List<RoleSDO> loginUserRoles = new ArrayList<>();
        if(loginUserRolesResult!=null && CollectionUtils.isNotEmpty(loginUserRolesResult.getResult())){
            loginUserRoles = loginUserRolesResult.getResult();
        }
        //超级管理员不校验
        List<RoleSDO> admain = loginUserRoles.stream().filter(x->RoleQueryServiceImpl.ADMIN_ROLE_ID.equals(x.getId())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(admain)) {
            return Result.success(true);
        }
        //业务管理员不校验
        if (StringUtils.isNotBlank(BcOrderConstants.BIZ_ADMIN_ROLE_CODE())) {
            List<String> bizAdminRoleCodeList = Arrays.asList(BcOrderConstants.BIZ_ADMIN_ROLE_CODE().split(","));
            List<RoleSDO> bizAdmin = loginUserRoles.stream().filter(x->bizAdminRoleCodeList.contains(x.getCode())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(bizAdmin)) {
                return Result.success(true);
            }
        }

        Set<String> loginUserBelongSys = loginUserRoles.stream().map(RoleSDO::getBelongOrganizationId).collect(Collectors.toSet());

        BaselineGetEmployeeRolesById2Request queryUpdateUserRoleReq = new BaselineGetEmployeeRolesById2Request();
        //queryUpdateUserRoleReq.setBelongOrganizationId(RoleQueryTypeEnum.OTS.getBelongOrganizationId());
        queryUpdateUserRoleReq.setEmployeeId(checkEmployeeSystemRequest.getUpdateUserId());
        Result<List<RoleSDO>> updateUserRolesResult = baseDataService.baselineGetEmployeeRolesById2(queryUpdateUserRoleReq);
        List<RoleSDO> updateUserRoles = new ArrayList<>();
        if(updateUserRolesResult!=null && CollectionUtils.isNotEmpty(updateUserRolesResult.getResult())){
            updateUserRoles = updateUserRolesResult.getResult();
        }
        Set<String> updateUserBelongSys = updateUserRoles.stream().map(RoleSDO::getBelongOrganizationId).collect(Collectors.toSet());

        if (!loginUserBelongSys.containsAll(updateUserBelongSys)) {
            throw new FacadeException(ErrorMessage.code("OTS-01-001-01-16-039"));
        }

        return Result.success(true);
    }



}

